
// 命名空间
/**
 * @description: ajax拦截类
 * @param {type} 
 * @return {type} 
 */
let ajax_interceptor = {
  settings: {
    ajaxInterceptor_switchOn: true,
    ajaxInterceptor_rules: [],
  },
  originalXHR: window.XMLHttpRequest,
  myXHR: function () {
    let pageScriptEventDispatched = false;
    const modifyResponse = () => {
      /**
       * @description: 拦截发票接口
       * @param {type} 
       * @return {type} 
       */
      if (!pageScriptEventDispatched) {
        // if (this.responseURL.indexOf("https://dev.w7.cc/v1/userInvoice") > -1) {
        if (this.responseURL == "https://dev.w7.cc/v1/userInvoice" ||this.responseURL.indexOf("https://dev.w7.cc/v1/userInvoice?") > -1) {
          var userInvoiceList = JSON.parse(this.response);
          console.log(userInvoiceList);
          window.dispatchEvent(new CustomEvent("pageScript", {
            detail: { userInvoiceList: userInvoiceList.invoice.data }
          }));
          pageScriptEventDispatched = true;
        }
      }

    }
    const xhr = new ajax_interceptor.originalXHR;
    for (let attr in xhr) {
      if (attr === 'onreadystatechange') {
        xhr.onreadystatechange = (...args) => {
          if (this.readyState == 4) {
            // 请求成功
            if (ajax_interceptor.settings.ajaxInterceptor_switchOn) {
              // 开启拦截
              modifyResponse();
            }
          }
          this.onreadystatechange && this.onreadystatechange.apply(this, args);
        }
        continue;
      } else if (attr === 'onload') {
        xhr.onload = (...args) => {
          // 请求成功
          if (ajax_interceptor.settings.ajaxInterceptor_switchOn) {
            // 开启拦截
            modifyResponse();
          }
          this.onload && this.onload.apply(this, args);
        }
        continue;
      }

      if (typeof xhr[attr] === 'function') {
        this[attr] = xhr[attr].bind(xhr);
      } else {
        // responseText和response不是writeable的，但拦截时需要修改它，所以修改就存储在this[`_${attr}`]上
        if (attr === 'responseText' || attr === 'response') {
          Object.defineProperty(this, attr, {
            get: () => this[`_${attr}`] == undefined ? xhr[attr] : this[`_${attr}`],
            set: (val) => this[`_${attr}`] = val,
            enumerable: true
          });
        } else {
          Object.defineProperty(this, attr, {
            get: () => xhr[attr],
            set: (val) => xhr[attr] = val,
            enumerable: true
          });
        }
      }
    }
  }
}
window.addEventListener("message", () => {
  window.XMLHttpRequest = ajax_interceptor.myXHR;
}, false);